import PySimpleGUI as sg
from PIL import Image
#from PyPDF2 import PdfFileWriter,PdfFileReader,PdfFileMerger
import os
import sys,fitz
import datetime
import hashlib




def pdfToImage(pdfPath, imagePath):

    startTime_pdf2img = datetime.datetime.now()  # 开始时间
    print("imagePath=" + imagePath)
    pdfDoc = fitz.open(pdfPath)
    for pg in range(pdfDoc.pageCount):
        page = pdfDoc[pg]
        rotate = int(0)
        # 每个尺寸的缩放系数为1.3，这将为我们生成分辨率提高2.6的图像。
        # 此处若是不做设置，默认图片大小为：792X612, dpi=72
        zoom_x = 2.33333333  # (1.33333333-->1056x816)   (2-->1584x1224)
        zoom_y = 2.33333333
        mat = fitz.Matrix(zoom_x, zoom_y).preRotate(rotate)
        pix = page.getPixmap(matrix=mat, alpha=False)
        if not os.path.exists(imagePath):  # 判断存放图片的文件夹是否存在
            os.makedirs(imagePath)  # 若图片文件夹不存在就创建
        pix.writePNG("{}/{}_images_{}.png".format(imagePath,pdfPath.split('/')[-1][0:-4],pg)) # 将图片写入指定的文件夹内
    endTime_pdf2img = datetime.datetime.now()  # 结束时间
    print('pdf2img时间=', (endTime_pdf2img - startTime_pdf2img).seconds)

def ImageClip(ImagePath,outImagePath,zoom):
    im = Image.open(ImagePath)
    imSize = im.size
    print(imSize)
    y_i = int(imSize[1]/zoom)
    x_i= int(imSize[0]/zoom)
    # box = (0,0,v,h)
    # clitIm = im.crop(box)
    y_c = 0
    x_c = 0
    xyar = []
    for x in range(zoom):
        for y in range(zoom):
            tup_xy = (x_c,y_c,x_c+x_i,y_c+y_i)
            xyar.append(tup_xy)
            x_c+=x_i
        y_c+=y_i
        x_c=0
    i = 0
    for box in xyar:
        clitIm = im.crop(box)
        clitIm.save('{}/{}_{}.png'.format(outImagePath,ImagePath.split('/')[-1][0:-4],i))
        i+=1

def ImageJoin(ImagePathList,outImagePath,direction):
	#参数 1.要拼接的图片的路径list 2.输出路径，3.方向垂直 y 还是  x 横向拼接 
	
	height = 0
	width = 0
	Image_inputs = []
	for ImagePath in ImagePathList:
		print("图片路径=》",ImagePath)
		im = Image.open(ImagePath)
		imSize = im.size
		print(imSize)
		y_imSize = imSize[1]
		height = height + int(y_imSize)
		width = width + int(imSize[0])
		Image_inputs.append(im)
	if direction == 'y':
		forWidth = int(Image_inputs[0].size[0])
		print("输出的宽度=>",forWidth)
		formImage = Image.new('RGB',(forWidth,height),(255,255,255))
		y = 0
		for imgObj in Image_inputs:
			formImage.paste(imgObj,(0,y))
			y = y + int(imgObj.size[1])
		formImage.save(outImagePath)

def ImageSplit(ImagePathList):
	i = 0
	for imagePath in ImagePathList:
		im = Image.open(imagePath)
		imSize = im.size
		width = int(int(imSize[0])/2)
		i_height = int(imSize[1])
		height = int(imSize[1])*2
		to_img = Image.new("RGB",(width,height),(255,225,215))
		i_1 = im.crop((0,0,width,i_height))
		i_2 = im.crop((width,0,width*2,height))
		to_img.paste(i_1,(0,0))
		to_img.paste(i_2,(0,i_height))
		to_img.save("{}_img.jpg".format(i))
		i=i+1

def showWindow():

    pdfToImage_layout = [
        [sg.I(key='_INPFILES_', enable_events=True), sg.FilesBrowse(button_text='选择文件',
                                                                    enable_events=True,
                                                                    target='_INPFILES_',
                                                                    file_types=(("All Files", "*.pdf"),))
         ],
        [sg.I(key='_OUTFILES_'), sg.FolderBrowse(button_text='输出路径',
                                                 target='_OUTFILES_', )],
        [sg.B(button_text='开始', key='_PDFTOIMAGE_')]
    ]

    imageClip_layout = [

        [sg.I(key='_INPImagesFiles_', enable_events=True), sg.FilesBrowse(button_text='选择图片',
                                                                          enable_events=True,
                                                                          target='_INPImagesFiles_',
                                                                          file_types=(("All Files", "*.png"),
                                                                                      ("All Files", "*.jpg"),))
         ],
        [sg.I(key='_OUTIMAGEFILES_'), sg.FolderBrowse(button_text='输出路径',
                                                      target='_OUTIMAGEFILES_', )],
        [sg.T('放大倍数'), sg.Slider((2, 10),
                                 disable_number_display=False,  # 是否显示当前刻度值
                                 default_value=2,  # 设置默认值
                                 orientation='h',
                                 key='_SLIDER_')  # 设置滑块是垂直还是水平 简写 h 或 v
         ],
        [sg.B(button_text='开始', key='_IMAGECLIP_')]

    ]

    imageJoin_layout = [

    	[sg.I(key='_INPFILESJOIN_', enable_events=True), sg.FilesBrowse(button_text='选择拼接图片',
                                                                          enable_events=True,
                                                                          target='_INPFILESJOIN_',
                                                                          file_types=(("All Files", "*.png"),
                                                                                      ("All Files", "*.jpg"),))
         ],
        [sg.I(key='_OUTFILESJOIN_'), sg.FolderBrowse(button_text='输出路径',
                                                      target='_OUTFILESJOIN_', )],
        [sg.T('输出文件名:'),sg.I(key='_UOTFILENAME_')],

        [
    	 sg.Radio('垂直拼接', "RADIO1", default=True,key="_Y_"),
   		 sg.Radio('横向拼接', "RADIO1",key="_X_")
   		 ],
        
        [sg.B(button_text='开始', key='_IMAGEJOIN_')]


    ]

    layout = [
        [sg.TabGroup([[
            sg.Tab('PDF转图片', layout=pdfToImage_layout),
            sg.Tab('图片切片', layout=imageClip_layout),
            sg.Tab('图片连接',layout=imageJoin_layout)
        ]]
            ,tab_location="lefttop"
            ,tab_background_color='#64778D'
            ,selected_background_color='#fff'
            ,selected_title_color='black'
            )]
    ]

    window = sg.Window("PDF", layout)

    while True:
        event,values = window.read()
        if event == None:
            break;
        if event == '_PDFTOIMAGE_':
            for k in values:
                if k =='_INPFILES_':
                    filses = values[k].split(';')
                    pass
                elif k == '_OUTFILES_':
                    outFile = values[k]
                    pass
            for fileName in filses:
                pdfToImage(fileName, outFile)
        if event == '_IMAGECLIP_':
            for k in values:
                if k =='_INPImagesFiles_':
                    Image_filses = values[k].split(';')
                    pass
                elif k == '_OUTIMAGEFILES_':
                    Image_outFile = values[k]
                    pass
                elif k == '_SLIDER_':
                    zoom = values[k]
            for filePath in Image_filses:
                ImageClip(filePath, Image_outFile, int(zoom))
        if event == '_IMAGEJOIN_':
            print("values=>",values)
            for k in values:
                if k =='_INPFILESJOIN_':
                    filses = values[k].split(';')
                    pass
                elif k == '_OUTFILESJOIN_':
                    outFile = values[k]
                    pass
                elif k == '_UOTFILENAME_':
                	name = values[k]
            if values["_X_"]:
            	direction = 'x'
            elif values["_Y_"]:
            	direction = 'y'
            ImageJoin(filses,outFile + '/' + name + '.jpg',direction)


    window.close()

#showWindow()

# ImagePath = r"图片/3.15活动工作思路_images_0.png"
# outImagePath = r'图片'
# zoom = 3
# ImageClip(ImagePath,outImagePath,zoom)
# filesList = []
# for root,dirs,files in os.walk(r'新建文件夹'):
# 	for file in files:
# 		filesList.append(os.path.join(root,file))
# print(filesList)




# ImageSplit(filesList)

# ImageJoin([r'2014少儿赞美乐谱j/1.梦想与异象A_images_0.jpg',r'2014少儿赞美乐谱j/1.梦想与异象B_images_0.jpg'],r'test.jpg','y')


filesList=[]
for root,dirs,files in os.walk(r'C:/Users/feili/Desktop/成品/明文'):
	for file in files:
		# filesList.append(os.path.join(root,file))
		m2 = hashlib.md5()
		print(file.split(".")[0])
		src = file.split(".")[0]
		m2.update(src.encode("utf8"))
		md5name = m2.hexdigest()
		print(os.path.join(root,file))
		fo = open(os.path.join(root,file),"rb")
		fi = open(os.path.join(root,md5name+'.jpg'),"wb")
		fi.write(fo.read())
		fi.close()
		fo.close()



